package cn.jly.spring.annotation.ioc.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

/**
 * @author lanyangji
 * @description 测试@Profile注解，根据当前环境切换一系列组件的功能
 * @date 2020/11/13 下午 5:39
 */
@Configuration
@PropertySource("classpath:db.properties")
public class MainConfigProfile {

    @Value("${db.username}")
    private String username;
    @Value("${db.password}")
    private String password;
    @Value("${jdbcClassName}")
    private String jdbcClassName;
    @Value("${jdbcUrl}")
    private String jdbcUrl;

    /**
     * 默认是default环境
     *
     * @return
     * @throws PropertyVetoException
     */
    @Profile("dev")
    @Bean
    public DataSource devDataSource() throws PropertyVetoException {
        final ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(username);
        dataSource.setPassword(password);
        dataSource.setJdbcUrl(jdbcUrl + "test");
        dataSource.setDriverClass(jdbcClassName);

        return dataSource;
    }

    @Profile("test")
    @Bean
    public DataSource testDataSource() throws PropertyVetoException {
        final ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(username);
        dataSource.setPassword(password);
        dataSource.setJdbcUrl(jdbcUrl + "students");
        dataSource.setDriverClass(jdbcClassName);

        return dataSource;
    }

    @Profile("prod")
    @Bean
    public DataSource prodDataSource() throws PropertyVetoException {
        final ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(username);
        dataSource.setPassword(password);
        dataSource.setJdbcUrl(jdbcUrl);
        dataSource.setDriverClass(jdbcClassName + "mapper");

        return dataSource;
    }
}
